﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class DataBaseViewForm : Form
    {

        const string GetSchemaQuery = @"select * from sqlite_master";
        const string ConnectionString = @"Data Source=d:\db\main.db;";

        public DataBaseViewForm()
        {
            InitializeComponent();
            textBoxQuery.Text = GetSchemaQuery;

            dataGridResultsView.ReadOnly = true;
            dataGridResultsView.DataError += dataGridResultsView_DataError;
        }

        void dataGridResultsView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           Bind(textBoxQuery.Text);
        }

        private void buttonGetSchema_Click(object sender, EventArgs e)
        {
            Bind(GetSchemaQuery);
        }

        private async void Bind(string query)
        {
            try
            {
                await Bind(dataGridResultsView, query);
            }
            catch (System.Data.Common.DbException ex)
            {
                MessageBox.Show(ex.ToString());
            }                
        }

        private async Task Bind(DataGridView view, string query)
        {
            using (var factory = new System.Data.SQLite.SQLiteFactory())
            {
                using (var connection = factory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;

                    var command = connection.CreateCommand();
                    command.CommandText = query;

                    connection.Open();
                    var reader = await command.ExecuteReaderAsync();

                    var table = new DataTable();
                    table.Load(reader);
                    view.DataSource = table;
                }
            }
        }
    }
}
